package com.xdf.zipperdye.service;

import com.xdf.zipperdye.dao.business.SysUserMapper;
import com.xdf.zipperdye.model.*;
import com.xdf.zipperdye.utils.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper dao;

    @Autowired
    private SysPermissionService permService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private TableStyleService tsService;

    @Override
    public int deleteByPrimaryKey(Integer iid) {
        return dao.deleteByPrimaryKey(iid);
    }

    @Override
    public SysUser insert(SysUser record) {
        record.setIid(null);
        if (isExist(record.getUserid()) == true)
            throw new BusinessException("编号：" + record.getUserid() + ",已经存在！");
        int ret = dao.insert(record);
        String roleNames = resolveRoleNames(record.getIid(), record.getRole_iids());
        record.setRole_sids(roleNames);
        return updateByPrimaryKey(record);
    }

    @Override
    public SysUser insertSelective(SysUser record) {
        record.setIid(null);
        if (isExist(record.getUserid()) == true)
            throw new BusinessException("编号：" + record.getUserid() + ",已经存在！");
        int ret = dao.insertSelective(record);
        String roleNames = resolveRoleNames(record.getIid(), record.getRole_iids());
        record.setRole_sids(roleNames);
        return updateByPrimaryKey(record);
    }

    @Override
    public SysUser selectByPrimaryKey(Integer iid) {
        return dao.selectByPrimaryKey(iid);
    }

    @Override
    public SysUser updateByPrimaryKeySelective(SysUser record) {
        // 清空表 sys_user_role 中关于用户 record.getIid() 的所有数据
        // 重新写入用户对应的角色记录，同时返回角色的名称字符串
        String roleNames = resolveRoleNames(record.getIid(), record.getRole_iids());
        record.setRole_sids(roleNames);
        int ret = dao.updateByPrimaryKeySelective(record);
        return selectByPrimaryKey(record.getIid());
    }

    @Override
    public SysUser updateByPrimaryKey(SysUser record) {
        // 清空表 sys_user_role 中关于用户 record.getIid() 的所有数据
        // 重新写入用户对应的角色记录，同时返回角色的名称字符串
        String roleNames = resolveRoleNames(record.getIid(), record.getRole_iids());
        record.setRole_sids(roleNames);
        int tmp = dao.updateByPrimaryKey(record);
        SysUser ret = selectByPrimaryKey(record.getIid());
        return ret;
    }

    @Override
    public List<SysUser> selectAll() {
        return dao.selectAll();
    }

    @Override
    public SysUser selectByUserId(String userid) {
        return dao.selectByUserId(userid);
    }

    @Override
    public boolean isExist(String userid) {
        if (userid == null || userid.length() <= 0) return false;
        SysUser record = dao.selectByUserId(userid);
        return record == null ? false : true;
    }

    @Override
    public List<SysRolep> selectUserObjPermissions(String userid) {
        return dao.selectUserObjPermissions(userid);
    }

    /**
     * 根据工号查询获取用户的权限 - 拥有哪些请求的权限
     * 可能一个权限对应了多个请求
     *
     * @param userid 用户工号 = sys_user.userid
     * @return
     */
    @Override
    public List<SysPermission> selectPermissionsByUserId(String userid) {
        List<SysRolep> objPerms = selectUserObjPermissions(userid);
        if (objPerms == null || objPerms.size() <= 0) return null;
        List<SysPermission> ret = new ArrayList<>();
        objPerms.forEach(item -> {// 遍历 - sys_rolep 按照对象主键汇总的记录集
            // 填充查看权限的请求
            if (item.getPermission_view() == true) {// 枚举每个权限赋值
                List<SysPermission> perms = permService.selectByObjPerm(item.getObject_iid(), "view");
                if (perms != null && perms.size() > 0) {
                    for (SysPermission perm : perms) {
                        ret.add(perm);
                    }
                }
            }

            // 填充新增权限的请求
            if (item.getPermission_new() == true) {// 枚举每个权限赋值
                List<SysPermission> perms = permService.selectByObjPerm(item.getObject_iid(), "new");
                if (perms != null && perms.size() > 0) {
                    for (SysPermission perm : perms) {
                        ret.add(perm);
                    }
                }
            }

            // 填充修改权限的请求
            if (item.getPermission_update() == true) {// 枚举每个权限赋值
                List<SysPermission> perms = permService.selectByObjPerm(item.getObject_iid(), "update");
                if (perms != null && perms.size() > 0) {
                    for (SysPermission perm : perms) {
                        ret.add(perm);
                    }
                }
            }

            // 填充删除权限的请求
            if (item.getPermission_delete() == true) {// 枚举每个权限赋值
                List<SysPermission> perms = permService.selectByObjPerm(item.getObject_iid(), "delete");
                if (perms != null && perms.size() > 0) {
                    for (SysPermission perm : perms) {
                        ret.add(perm);
                    }
                }
            }

            if (item.getPermission_money() == true) {// 枚举每个权限赋值
                List<SysPermission> perms = permService.selectByObjPerm(item.getObject_iid(), "money");
                if (perms != null && perms.size() > 0) {
                    for (SysPermission perm : perms) {
                        ret.add(perm);
                    }
                }
            }
        });
        return ret;
    }

    @Override
    public List<SysRole> selectRoles(int iid) {
        return dao.selectRoles(iid);
    }

    @Override
    public FusedUserRole selectFusedUser(int iid) {
        SysUser user = selectByPrimaryKey(iid);
        if (user == null) throw new BusinessException("没有查询到该用户！");
        FusedUserRole fuser = new FusedUserRole();
        // 复制其他属性
        fuser.setIid(user.getIid());
        fuser.setUserid(user.getUserid());
        fuser.setUsername(user.getUsername());
        fuser.setPassword(user.getPassword());
        fuser.setRemark(user.getRemark());
        fuser.setNon_locked(user.getNon_locked());
        fuser.setNon_expired(user.getNon_expired());
        fuser.setNon_password_expired(user.getNon_password_expired());
        fuser.setStatus(user.getStatus());
        fuser.setLast_time(user.getLast_time());
        fuser.setCreate_time(user.getCreate_time());

        // 设置角色数组
        List<SysRole> roles = selectRoles(iid);
        if (roles != null && roles.size() > 0) {
            fuser.setSysRoles(roles);

            List<Integer> roleIids = new ArrayList<>();
            roles.forEach(item -> {
                roleIids.add(item.getIid());
            });
            fuser.setRoleIids(roleIids);
        }

        return fuser;
    }

    /**
     * 2020年2月22日09:04:52，过滤金额权限返回表样式数据
     *
     * @param userid    用户字符串ID = sys_user.userid
     * @param tableName 表名称 = table_style.table_name
     * @return
     */
    @Override
    public List<TableStyle> selectTableStyleByUserId(String userid, String tableName) {
        if (userid == null || userid.length() <= 0) throw new BusinessException("用户编号为空！");
        List<SysRolep> objPerms = selectUserObjPermissions(userid);
        if (objPerms == null || objPerms.size() <= 0) throw new BusinessException("该用户没有任何权限！");

        SysRolep perm = objPerms.get(0);
        Boolean money = perm.getPermission_money();

        List<TableStyle> ts = tsService.selectByTableName(tableName);
        if (ts == null || ts.size() <= 0) throw new BusinessException("没有查询到表的样式数据！");

        for (int i = 0; i < ts.size() - 1; i++) {
            if (ts.get(i).getPerm_money() == 1 && money == false) {
                ts.remove(i);
            }
        }
        return ts;
    }


    /**
     * 向表 sys_user_role 重写用户对应角色记录集，同时返回角色名称字符串
     *
     * @param userIid  用户主键
     * @param roleIids 角色主键构成的字符串
     * @return
     */
    public String resolveRoleNames(int userIid, String roleIids) {
        if (roleIids == null || roleIids.length() <= 0) return "";
        List<SysRole> roles = roleService.selectByPks(roleIids);
        if (roles == null || roles.size() <= 0) return "";

        String roleNames = "";
        userRoleService.deleteByUserIid(userIid);
        for (SysRole role : roles) {
            SysUserRole tmp = new SysUserRole();
            tmp.setUser_pk(userIid);
            tmp.setRole_pk(role.getIid());
            userRoleService.insertSelective(tmp);
            roleNames = roleNames + role.getRoleid() + ",";
        }

        if (roleNames.substring(roleNames.length() - 1).equals(","))
            roleNames = roleNames.substring(0, roleNames.length() - 1);

        return roleNames;
    }
}